<?php


namespace app\model;

use think\facade\Cache;
use think\facade\Db;
use think\response\Json;
use Exception as E;

class BackStoreModel
{
    private static $_table = 'eb_store'; // 商户表
    private static $_adminTable = 'eb_admin'; // 管理员表
    private static $_goodsTable = 'eb_goods'; // 商品表
    private static $_cateTable = 'eb_category'; // 商品分类表
    private static $_orderTable = 'eb_order'; // 订单表
    private static $_orderDetailTable = 'eb_order_detail'; // 订单详情
    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['a.id', '=', $admin['id']];
            if ($input['name'] !== '') $map[] = ['g.name', 'like', "%{$input['name']}%"];
            if ($input['cate_name'] !== '') $map[] = ['c.name', 'like', "%{$input['cate_name']}%"];
            if ($input['is_show'] !== '') $map[] = ['g.is_show', '=', $input['is_show']];
            $field = 'g.id,c.name as cate_name,c.type as cate_type,g.name as goods_name,g.pic,g.price,g.detail,g.is_out,g.is_show,g.stock,g.meat_num,g.veg_num,FROM_UNIXTIME(g.create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_goodsTable)->alias('g')
                ->leftJoin([self::$_table => 's'], 's.id = g.store_id')
                ->leftJoin([self::$_cateTable => 'c'], 'c.id = g.cate_id')
                ->leftJoin([self::$_adminTable => 'a'], 'a.id = s.admin_id')
                ->field($field)
                ->where($map);
            $count  = $table->count();
            if ($count == 0) return jsonSuccess('获取成功！', ['count' => $count, 'list' => []]);
            $data = $table->order('g.create_time', 'desc')->page($input['page'],$input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $data]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**修改商品状态
     * @param $input
     * @param $token
     * @return Json
     */
    public static function changeGoodsStatus($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['id', '=', $input['id']],
                [$input['name'], '=', $input['status'] == 1 ? 0 : 1]
            ];
            $update = [
                $input['name'] => $input['status']
            ];
            Db::startTrans();
            $flag = true;
            $res = Db::table(self::$_goodsTable)->where($map)->update($update);
            if ($res) {
                $rtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' . $input['id'], $update);
                if ($rtn === true) {
                    Db::commit();
                    return jsonSuccess('修改成功');
                }
            }
            Db::rollback();
            return jsonFail('修改失败');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**批量下架商品
     * @param $input
     * @param $token
     * @return Json
     */
    public static function multiOff($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['id', 'in', $input['ids']],
            ];
            $update = [
                'is_show' => 0
            ];
            $res = Db::table(self::$_goodsTable)->where($map)->update($update);
            if ($res) {
                foreach ($input['ids'] as $id) {
                    Cache::store('redis')->handler()->hMset('dxsd-goods-' . $id, $update);
                }
                return jsonSuccess('修改成功');
            }
            return jsonFail('修改失败');
        } catch (E $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }
    /**获取商品分类列表
     * @param $token
     * @return Json
     */
    public static function findCateList($token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $res = Db::table(self::$_cateTable)->field('id,name,type')->select()->toArray();
            if ($res) return jsonSuccess('获取成功', $res);
            return jsonFail('获取失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 添加商品
     * @param $input
     * @param $token
     * @return Json
     */
    public static function  addGoods($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            // 获取商户id
            $storeId = Db::table(self::$_table)->where('admin_id', $admin['id'])->value('id');
            if (!$storeId) return jsonFail('未找到商户信息');
            $cateInfo = explode('-', $input['cate_id']);
            $input['cate_id'] = $cateInfo[0];
            $input['type'] = $cateInfo[1];
            $input['create_time'] = time();
            $input['store_id'] = $storeId;
            $input['meat_num'] = 0;
            $input['veg_num'] = 0;
            $input['is_out'] = 0;
            Db::startTrans();
            $flag = true;
            $id = Db::table(self::$_goodsTable)->insertGetId($input);
            if (!$id) {
                Db::rollback();
                return jsonSuccess('添加失败');
            }
            $rtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' . $id, $input);
            if ($rtn === true) {
                Db::commit();
                return jsonSuccess('添加成功');
            }
            Db::rollback();
            return jsonSuccess('添加失败');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /** 编辑商品可售数量
     * @param $input
     * @param $token
     * @return Json
     */
    public static function  editNum($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            // 获取商户id
            $storeId = Db::table(self::$_table)->where('admin_id', $admin['id'])->value('id');
            if (!$storeId) return jsonFail('未找到商户信息');
            $input[$input['name']] = $input['num'];
            unset($input['name']);
            unset($input['num']);
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_goodsTable)->update($input);
            if ($rtn) {
                $redisRtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' . $input['id'], $input);
                if ($redisRtn === true) {
                    Db::commit();
                    return jsonSuccess('编辑成功');
                }
            }
            Db::rollback();
            return jsonSuccess('编辑失败');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }


    /** 获取单个商品信息
     * @param $input
     * @param $token
     * @return Json
     */
    public static function goodsOnly($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            // 获取单个信息
            $map[] = ['id', '=', $input['id']];
            $rtn = Db::table(self::$_goodsTable)->field("id,CONCAT_WS('-',cate_id,type) as cate_id,name,pic,price,detail,stock")->where($map)->find();
            if ($rtn) return jsonSuccess('获取成功', $rtn);
            return jsonFail('未找到信息');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /** 编辑商品
     * @param $input
     * @param $token
     * @return Json
     */
    public static function editGoods($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $cateInfo = explode('-', $input['cate_id']);
            if ($cateInfo[1] == 1) {
                $input['meat_num'] = 0;
                $input['veg_num'] = 0;
            }
            $input['cate_id'] = $cateInfo[0];
            $input['type'] = $cateInfo[1];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_goodsTable)->update($input);
            if (!$rtn) {
                Db::rollback();
                return jsonSuccess('编辑失败');
            }
            $rtn = Cache::store('redis')->handler()->hMset('dxsd-goods-' .  $input['id'], $input);
            if ($rtn === true) {
                Db::commit();
                return jsonSuccess('编辑成功');
            }
            Db::rollback();
            return jsonSuccess('编辑失败');
        } catch (E $e) {
//            var_dump($e->getMessage());
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**删除商品
     * @param $input
     * @param $token
     * @return Json
     */
    public static function deleteGoods($input, $token)
    {
        $flag = false;
        try {
            /// 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            // 获取商品图片
            $pic = Db::table(self::$_goodsTable)->where('id', $input['id'])->value('pic');
            $picPath = substr(app()->getRootPath(),0,-5) . $pic;
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_goodsTable)->where('id', $input['id'])->delete();
            if ($rtn) {
                // 删除缓存
                $delRtn = Cache::store('redis')->handler()->del('dxsd-goods-' . $input['id']);
                if ($delRtn === 0) {
                    Db::rollback();
                    return jsonFail('删除失败');
                } else {
                    Db::commit();
                    @unlink($picPath);
                    return jsonSuccess('删除成功');
                }
            } else {
                Db::rollback();
                return jsonFail('未找到数据,请先刷新确认');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取销售列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getSellList($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['o.store_id', '=', $admin['store_id']];
            $map[] = ['o.status', 'in', [-3,6,7]];
            if ($input['start'] !== '') $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            if ($input['end'] !== '') $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            if ($input['name'] !== '') $map[] = ['od.goods_name', 'like', "%{$input['name']}%"];
            $field = 'od.goods_name,sum(od.goods_num) as sell_num,od.type';
            $table = Db::table(self::$_orderTable)->alias('o')
                ->leftJoin([self::$_orderDetailTable => 'od'], 'o.id = od.order_id')
                ->field($field)
                ->where($map)->group('od.goods_id');
            $count  = $table->count();
            if ($count == 0) return jsonSuccess('获取成功！', ['count' => $count, 'list' => []]);
            $data = $table->order('sell_num', 'desc')->page($input['page'],$input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $data]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取订单列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getOrderList($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [5]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['store_id', '=', $admin['store_id']];
            if ($input['status'] !== '') $map[] = ['status', '=', $input['status']];
            if ($input['is_pay'] !== '') $map[] = ['is_pay', '=', $input['is_pay']];
            if ($input['financial_status'] !== '') $map[] = ['financial_status', '=', $input['financial_status']];
            if ($input['start'] !== '') $map[] = ['create_time', '>=', strtotime($input['start'])];
            if ($input['end'] !== '') $map[] = ['create_time', '<=', strtotime($input['end'])];
            $field = 'order_no,total_price,goods_price,status,comment,is_pay,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_orderTable)
                ->field($field)
                ->where($map);
            $count  = $table->count();
            if ($count == 0) return jsonSuccess('获取成功！', ['count' => $count, 'list' => []]);
            $data = $table->order('create_time', 'desc')->page($input['page'],$input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $data]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**商家财务获取订单列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getFinanceOrderList($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [6]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['store_id', '=', $admin['store_id']];
            $map[] = ['status', 'in', '-3,6,7'];
//            if ($input['status'] === '') {
//                $map[] = ['status', 'in', '-3,6,7'];
//            } else {
//                $map[] = ['status', '=', $input['status']];
//            }
            if ($input['start'] !== '') $map[] = ['create_time', '>=', strtotime($input['start'])];
            if ($input['end'] !== '') $map[] = ['create_time', '<=', strtotime($input['end'])];
            $field = 'order_no,goods_price,status,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_orderTable);
            $rtn  = $table->field('count(*) as count,sum(goods_price) as money')->where($map)->find();
            if ($rtn['count'] == 0) return jsonSuccess('获取成功！', ['count' => 0, 'money' =>0,'list' => []]);
            $data = $table->removeOption('field')->field($field)->order('create_time', 'desc')->page($input['page'],$input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $rtn['count'],'money'=> $rtn['money'], 'list' => $data]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**学校财务获取订单列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getSchFinanceOrderList($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [7]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['a.school_id', '=', $admin['school_id']];
            $map[] = ['o.status', 'in', '-3,6,7'];
//            if ($input['status'] === '') {
//                $map[] = ['o.status', 'in', '-3,6,7'];
//            } else {
//                $map[] = ['o.status', '=', $input['status']];
//            }

            if ($input['start'] !== '') $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            if ($input['end'] !== '') $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            if ($input['name'] !== '') $map[] = ['s.shop_name', 'like', "%{$input['name']}%"];
            $field = 's.shop_name,o.order_no,goods_price,o.status,FROM_UNIXTIME(o.create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_adminTable)->alias('a')
                ->join([self::$_orderTable => 'o'], 'a.school_id = o.school_id')
                ->join([self::$_table =>'s'], 's.id = o.store_id');
            $rtn  = $table->field('count(*) as count,sum(goods_price) as money')->where($map)->find();
            if ($rtn['count'] == 0) return jsonSuccess('获取成功！', ['count' => 0, 'money' =>0,'list' => []]);
            $data = $table->removeOption('field')->field($field)->order('o.create_time', 'desc')->page($input['page'],$input['limit'])->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $rtn['count'],'money'=> $rtn['money'], 'list' => $data]);
        } catch (E $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }
}